<template>
  <div>
    <el-table
    ref="tableRef"
      :data="tableData"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
      border
      default-expand-all
      @select="select"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="date" label="Date" sortable />
      <el-table-column prop="name" label="Name" sortable />
      <el-table-column prop="address" label="Address" sortable />
    </el-table>

  </div>
</template>
<script  setup>
import { ref ,reactive, onMounted} from 'vue'
const tableRef = ref('')
const state = reactive({
selectedIdList: [3]
})
onMounted(()=>{
  // treeForeach(tableData[2])
  // tableRef.value.toggleRowSelection(tableData[2], true);
  // tableRef.value.toggleRowSelection(tableData[2].children[1], false);
  // 初始化第一次时，勾中父节点，遍历子节点看是否选中来，设置状态
})
// 表格手动勾选
const select = (row) => {
    // 判断该节点之前是否选中
    if (state.selectedIdList.indexOf(row.id) > -1) {
        // 选中，则取消选中，从selectedIdList中删除
        state.selectedIdList.map((item, index) => {
            if (item == row.id) {
                state.selectedIdList.splice(index, 1);
            }
        });
    } else {
        // 未选中，则选中，添加到selectedIdList中
        state.selectedIdList.push(row.id);
    }
    //
    treeForeach(row);
};

// 遍历节点，设置选中状态
const treeForeach = (tree) => {
    // 选中的节点是否是父节点
    if (tree.children && tree.children.length > 0) {
        // 是
        tree.children.forEach((item) => {
            // 判断该节点之前是否选中
            if (state.selectedIdList.indexOf(item.id) > -1) {
              console.log('--1');
                // 子节点原先被选中
                tableRef.value.multipleTableRef.toggleRowSelection(item, true);
            } else {
              console.log('--  -1');

                // 子节点原先未选中
                tableRef.value.multipleTableRef.toggleRowSelection(item, false);
            }
            treeForeach(item);
        });
    }
};



 const tableData = [
  {
    id: 1,
    date: '2016-05-02',
    name: 'wangxiaohu',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    id: 2,
    date: '2016-05-04',
    name: 'wangxiaohu',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    id: 3,
    date: '2016-05-01',
    name: 'wangxiaohu',
    address: 'No. 189, Grove St, Los Angeles',
    children: [
      {
        id: 31,
        date: '2016-05-01',
        name: 'wangxiaohu',
        address: 'No. 189, Grove St, Los Angeles',
      },
      {
        id: 32,
        date: '2016-05-01',
        name: 'wangxiaohu',
        address: 'No. 189, Grove St, Los Angeles',
      },
    ],
  },
  {
    id: 4,
    date: '2016-05-03',
    name: 'wangxiaohu',
    address: 'No. 189, Grove St, Los Angeles',
  },
]

</script>
